<template>
	<view class="outbound">
		<view class="nav-style"
			:style="{ height: navHeight - 15 + 'px', 'padding-top': 15 + 'px', lineHeight: navHeight + 'px', fontWeight: 600, fontSize: 18 + 'px' }">
			<image style="width: 40rpx; height: 40rpx" src="/static/image/back.png" mode="aspectFit" @click="back">
			</image>
			入库
		</view>

		<view style="background-color: #f4f6f8; padding: 12px 15px">
			<view class="content" :style="{ marginTop: navHeight + 'px' }">
				<view class="one">
					<text class="label">入库操作人员</text>
					<!-- <uni-easyinput input-class="custom-input-class" v-model="Info.deviceno" placeholder="请输" /> -->
					<text>{{ Info.name }}</text>
				</view>
				<view class="one">
					<text class="label">入库时间</text>
					<uni-datetime-picker :border="false" type="datetime" valueFormat="yyyy-MM-dd HH:mm:ss"
						placeholder="请选择入库时间" v-model="Info.outtime" />
				</view>
				<!-- 	<view class="one">
					<span class="label">关联项目</span>
					<view class="" style="width: 70%">
						<uni-data-select :value="Info.projectid" :localdata="projectList" @change="changeProject"></uni-data-select>
					</view>
				</view> -->
				<view class="one" style="margin-top: 10rpx; height: 400rpx">
					<text class="label">设备编号</text>
					<view>
						<scroll-view scroll-y="true" class="scroll-Y">
							<view class="scroll-view-item" style="display: flex; align-items: center"
								v-for="item in deviceList" :key="item">
								<text
									style="display: inline-block; padding: 10rpx; background-color: #e9f8f7; margin-right: 10rpx; border-radius: 10rpx">{{ item }}</text>
								<uni-icons type="close" size="24" color="#c7c1bc" @click="removeOne(item)"></uni-icons>
							</view>
						</scroll-view>
					</view>
					<view class="icon">
						<view class="clearall" @click="deviceList = []">清空</view>
						<view @click="addOne" style="margin-left: 20rpx; margin-top: 60rpx">
							<uni-icons type="plus" size="24" color="#E10000"></uni-icons>
						</view>
						<view @click="sys" style="margin-left: 20rpx; margin-top: 60rpx">
							<image src="/static/image/sys.png" mode=""></image>
						</view>
					</view>
				</view>
				<view class="one">
					<text class="label">设备数量</text>
					<!-- <uni-easyinput input-class="custom-input-class" type="number" v-model="devNum" /> -->
					<text>{{ devNum ? devNum : '' }}</text>
				</view>

				<!-- 标签名称选择器 -->
				<picker @change="bindPickerChange" mode="selector" :value="tagIndex" :range="tabArray"
					range-key="labelname" v-if="tabArray.length!=0">
					<view class="one">
						<text class="label">标签名称</text>
						<!-- <uni-easyinput input-class="custom-input-class" type="number" v-model="devNum" /> -->
						<text>{{ tabArray[tagIndex]?.labelname || '请选择标签' }}</text>
					</view>
				</picker>
				
				<view class="one" v-if="tabArray.length==0">
					<text class="label">标签名称</text>
					<!-- <uni-easyinput input-class="custom-input-class" type="number" v-model="devNum" /> -->
					<text>暂无标签</text>
				</view>

			</view>
		</view>
		<view class="btn-box">
			<button class="btn" @click="onSubmit">入库</button>
		</view>

		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="添加" duration="0" :before-close="true" @close="close"
				v-model="deviceno" placeholder="请输入单个设备编号" @confirm="confirm" maxlength="13"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import store from '@/store';
	import {
		debounce
	} from '@/utils/util.js';
	import {
		FindLoginUser,
		addDevice,
		getActivityList,
		getDevice,
		VerifyPermissions,
		BatchVerifyPermissions,
		GetLabelsForAdminAsync
	} from '../../utils/api';
	let that = null;
	export default {
		data() {
			return {
				Info: {
					outtime: ''
				},
				currentDate: new Date().toISOString().split('T')[0] + ' ' + new Date().toISOString().split('T')[1].split(
					'.')[0],
				projectList: [],
				statusBarHeight: '',
				navHeight: '',
				num: '',
				deviceno: '',
				deviceList: [],
				tabArray: [],
				tagIndex: null,
				labelnameid:null,
			};
		},
		onShow() {
			this.FindLoginUser();
		},
		onLoad() {
			this.getActivityList();
			that = this;
			//获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
			uni.getSystemInfo({
				success: (e) => {
					// this.compareVersion(e.SDKVersion, '2.5.0')
					let statusBar = 0;
					let customBar = 0;
					// #ifdef MP
					statusBar = e.statusBarHeight;
					customBar = e.statusBarHeight + 45;
					if (e.platform === 'android') {
						// this.$store.commit('SET_SYSTEM_IOSANDROID', false)
						customBar = e.statusBarHeight + 50;
					}
					// #endif
					// #ifdef MP-WEIXIN
					statusBar = e.statusBarHeight;
					// @ts-ignore
					const custom = wx.getMenuButtonBoundingClientRect();
					customBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif

					// #ifdef APP-PLUS
					console.log('app-plus', e);
					statusBar = e.statusBarHeight;
					customBar = e.statusBarHeight + 45;
					// #endif

					// #ifdef H5
					statusBar = 0;
					customBar = e.statusBarHeight + 45;
					// #endif

					// 这里你可以自己决定存放方式，建议放在store中，因为store是实时变化的
					this.statusBarHeight = statusBar;
					this.navHeight = customBar;
				}
			});
		},
		beforeDestroy() {
			that = null;
		},
		computed: {
			devNum() {
				return this.deviceList.length;
			}
		},
		methods: {
			back() {
				uni.navigateBack();
			},
			addOne() {
				this.$refs.inputDialog.open();
			},
			async FindLoginUser() {
				const res = await FindLoginUser();
				console.log('findloginuser', res.data);
				if (res.code == 200) {
					this.Info.outuserid = res.data.userid;
					this.Info.username = res.data.admininfo.address.name;
					this.Info.name = res.data.admininfo.name;
					this.getTabData(res.data.userid)
					console.log(this.Info.outuserid);
				} else if (res.code == 502) {
					uni.showToast({
						title: '需重新登录',
						icon: 'none'
					});
					this.$store.commit('$uStore', {
						name: 'vx_token',
						value: ''
					});
					console.log(this.$store.state);
					uni.navigateTo({
						url: '/pages/login/index'
					});
				}
			},
			changeProject(e) {
				console.log(e);
				this.Info.projectid = e.toString();
				console.log(this.Info.projectid);
			},
			getActivityList() {
				getActivityList().then((res) => {
					console.log(res.data);
					if (res.code == 200) {
						res.data.forEach((item) => {
							this.projectList.push({
								value: item.id,
								text: item.name
							});
						});
					}
				});
			},
			// 扫码
			sys() {
				var that = this;
				uni.scanCode({
					success: function(res) {
						console.log(res);
						if (res.result.includes('JNA')) {
							// 普通二维码或条形码
							if (res.result.length > 50) {
								// 中白盒
								let devs = res.result.split(',').filter((item) => item !== ''); // 设备编号数组
								let commonitem = that.deviceList.filter((item) => devs.includes(item));
								let uniqueitem = that.deviceList.filter((item) => !devs.includes(item)).concat(
									devs.filter((item2) => !that.deviceList.includes(item2)));
								if (commonitem.length) {
									uni.showToast({
										icon: 'none',
										duration: 2000,
										title: `扫描的设备编号中${commonitem.length}个已存在`
									});
								} else {
									that.BatchVerifyPermissions(uniqueitem);
								}
							} else {
								// 单个
								console.log('测试', res.result);
								if (res.result.length == 13) {
									// 条形码
									if (that.deviceList.includes(res.result)) {
										uni.showToast({
											icon: 'none',
											duration: 2000,
											title: '该设备编号已存在'
										});
									} else {
										that.VerifyPermissions(res.result);
									}
								} else {
									// 二维码
									// console.log('当前设备',res.result.split(","));
									if (that.deviceList.includes(res.result.split(',')[1])) {
										uni.showToast({
											icon: 'none',
											duration: 2000,
											title: '该设备编号已存在'
										});
									} else {
										console.log('当前设备', res.result.split(',')[1]);
										that.VerifyPermissions(res.result.split(',')[1]);
									}
								}
							}
						} else if (res.result.includes('https://www.shlxkj.info:44313/ScanCodePanel')) {
							// 大箱码
							const queryStr = res.result.split('?')[1] || '';
							const params = queryStr.split('&');
							const batchno = params[0].split('=')[1];
							const code = params[1].split('=')[1];
							const data = {
								livecodeid: batchno,
								count: code
							};
							getDevice(data).then((res2) => {
								console.log(res2.data.devicenos);
								let commonitem = that.deviceList.filter((item) => res2.data.devicenos
									.includes(item));
								let uniqueitem = that.deviceList
									.filter((item) => !res2.data.devicenos.includes(item))
									.concat(res2.data.devicenos.filter((item2) => !that.deviceList
										.includes(item2)));
								console.log(commonitem);
								console.log(uniqueitem);
								if (commonitem.length) {
									uni.showToast({
										icon: 'none',
										duration: 2000,
										title: `扫描的设备编号中${commonitem.length}个已存在`
									});
								} else {
									that.BatchVerifyPermissions(uniqueitem);
								}
							});
						} else {
							uni.showToast({
								icon: 'none',
								duration: 2000,
								title: '请扫描正确的二维码或条形码'
							});
						}
					}
				});
			},
			// 单个
			VerifyPermissions(val) {
				VerifyPermissions(val)
					.then((res) => {
						if (res.code == 200) {
							if (res.data) {
								// 有权限添加
								this.deviceList.push(val);
								uni.showToast({
									icon: 'success',
									duration: 500
								});
								console.log(this.deviceList);
							} else {
								// 无权限添加
								uni.showToast({
									icon: 'none',
									duration: 2000,
									title: res.message
								});
							}
						} else {
							uni.showToast({
								icon: 'error',
								duration: 2000,
								title: res.message
							});
						}
					})
					.catch((err) => {
						uni.showToast({
							icon: 'none',
							title: '操作失败,请联系管理员处理'
						});
					});
			},
			// 批量
			BatchVerifyPermissions(devs) {
				BatchVerifyPermissions(devs)
					.then((res) => {
						console.log(res);
						console.log(this.deviceList);
						if (res.code == 200) {
							if (res.data) {
								this.deviceList = devs;
								uni.showToast({
									icon: 'success',
									duration: 1000
								});
								console.log(this.deviceList);
							} else {
								uni.showToast({
									icon: 'none',
									duration: 2000,
									title: res.message
								});
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '操作失败,请联系管理员处理'
							});
						}
					})
					.catch((err) => {
						uni.showToast({
							icon: 'none',
							title: '操作失败,请联系管理员处理'
						});
					});
			},
			confirm(e) {
				console.log(e);
				if (e.includes('JNA') && e.length == 13) {
					if (this.deviceList.includes(e)) {
						uni.showToast({
							icon: 'none',
							duration: 2000,
							title: '该设备编号已存在'
						});
					} else {
						this.VerifyPermissions(e);
						this.$refs.inputDialog.close();
					}
				} else {
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '请输入正确的设备编号'
					});
				}
			},
			close() {
				this.$refs.inputDialog.close();
			},
			//获取所有标签名称数据
			async getTabData(userid) {
				console.log('用户id',userid);
				let data = {
					adminid:userid,
					pagesize: 100,
					pageIndex: 1,
					labelname: "",
				}
				const res = await GetLabelsForAdminAsync(data);

				if (res.code == 200) {
					this.tabArray = res.data;
				}
			},
			//标签选择
			bindPickerChange(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.tagIndex = e.detail.value
				this.labelnameid=this.tabArray[e.detail.value].id
				console.log(this.labelnameid,'标签id');
			},
			removeOne(one) {
				const list = this.deviceList.filter((item) => item !== one);
				this.deviceList = list;
			},

			onSubmit: debounce(() => {
				console.log(that.Info.outtime);
				if (that.Info.outtime == '') {
					uni.showToast({
						icon: 'error',
						title: '请选择入库时间',
						duration: 2000
					});
					return;
				}
				if (that.deviceList.length) {
					uni.showLoading({
						title: '入库中..'
					});
					that.Info.deviceno = that.deviceList.toString();
					that.Info.labelnameid=that.labelnameid
					console.log(that.Info);
					addDevice(that.Info)
						.then((res) => {
							if (res.code == 200) {
								uni.hideLoading();
								uni.showToast({
									icon: 'success',
									title: '新增成功',
									duration: 2000
								});
								uni.switchTab({
									url: '/pages/module/index'
								});
								that.Info = {};
							} else {
								uni.showToast({
									icon: 'none',
									title: res.message,
									duration: 2000
								});
							}
						})
						.catch((err) => {
							console.log(err);
						});
				} else {
					uni.showToast({
						icon: 'error',
						title: '请输入设备编号',
						duration: 2000
					});
				}
			}, 500)

		}
	};
</script>

<style lang="scss" scoped>
	.outbound {
		height: 100vh;
		position: relative;

		.nav-style {
			background-image: url('https://www.shlxkj.info:10010/%E5%81%A5%E5%BA%B7%E6%A1%A3%E6%A1%88/zsafimg/bgimg.png');
			background-size: cover;
			background-repeat: no-repeat;
			position: fixed;
			top: 0;
			right: 0;
			left: 0;
			z-index: 1000;
			display: flex;
			padding-left: 23rpx;
			align-items: center;
			justify-content: center;

			image {
				position: absolute;
				left: 15px;
			}
		}

		.content {
			background-color: #fff;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			padding: 15rpx;

			.one {
				height: 84rpx;
				padding: 10rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid #f4f4f4;

				.label {
					color: #222222;
					font-weight: 500;
					font-size: 28rpx;
				}
			}

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.btn-box {
			background-color: #fff;
			padding: 40rpx;

			.btn {
				// width: 95%;
				height: 105rpx;
				// margin: 100rpx auto 0;
				color: #ffffff;
				font-weight: 500;
				font-size: 40rpx;
				background: linear-gradient(90deg, #a4edf1 0%, #00aeff 100%);
				box-shadow: 0rpx 8rpx 15rpx 0rpx rgba(14, 98, 122, 0.15);
				border-radius: 12rpx 12rpx 12rpx 12rpx;
			}
		}

		.scroll-Y {
			height: 400rpx;
		}

		.scroll-view-item {
			margin-bottom: 20rpx;
			// height: 50rpx;
			// line-height: 50rpx;
			text-align: center;
			// font-size: 36rpx;
		}

		.clearall {
			// margin-top: 40rpx;
			font-size: 26rpx;
			padding: 10rpx;
			border-radius: 10rpx;
			background-color: #e9f8f7;
		}

		// 输入框
		::v-deep .uni-easyinput__content {
			border-radius: 12rpx 12rpx 12rpx 12rpx;
		}

		::v-deep .uni-easyinput__content-input {
			height: 84rpx;
			text-align: right;
		}

		::v-deep .is-input-border {
			border: none;
		}

		::v-deep .uni-easyinput__placeholder-class {
			text-align: right;
		}

		::v-deep .content-clear-icon {
			display: none;
		}

		// 时间选择器
		::v-deep .uni-date-editor {
			text-align: right;
		}

		::v-deep.uni-date-x .uni-date-single {}

		::v-deep .icon-calendar {
			position: absolute;
			right: 0 !important;
		}

		::v-deep .uni-date__icon-clear {
			display: none;
		}

		::v-deep .uni-date__x-input {
			margin-right: 50rpx;
		}

		// 下拉框
		::v-deep .uni-select__input-text,
		.uni-select__input-placeholder {
			text-align: right;
			font-size: 14px;
		}

		::v-deep .uni-select {
			border: none;
		}

		// ::v-deep .uni-date__icon-clear {
		// 	display: none;
		// }

		.uni-forms-item {
			display: flex;
			align-items: center;
		}
	}
</style>